package com.lixiaohan.utils;

import com.aliyun.oss.OSSClient;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class OSSUtil {
    private String endpoint="oss-cn-chengdu.aliyuncs.com";//地域节点

    private String keyId="LTAI5t84GXzRaLWWVkjJTo8d";//访问id

    private String keySecret="ah9zGGkQ90JlfAEZ6JR38Nh3400S8c";//访问密钥

    private String bucketName="teaculture-001";//仓库名称

    private String suffer_url="http://teaculture-001.oss-cn-chengdu.aliyuncs.com/";//外网域名

    private SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");//日期格式化对象

    /**
     * 获取OSS连接
     */
    public OSSClient getOSSCLient(){
        //创建OSSCliet对象
        OSSClient ossClient = new OSSClient(endpoint, keyId, keySecret);
        //判断仓库是否存在
        if(ossClient.doesBucketExist(bucketName)) {
            System.out.println("bucket存在");
        }
//      else {
//            //通过api接口创建仓库
//            System.out.println("开始创建");
//            CreateBucketRequest bucketRequest=new CreateBucketRequest(null);
//            bucketRequest.setBucketName(bucketName);
//            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
//            ossClient.createBucket(bucketRequest);
////            ossClient.shutdown();
//        }
        return ossClient;
    }


    /**
     * 基于OSS实现文件上传
     */
    public String uploadDocument(MultipartFile file, String classify) throws IOException {
        //获取Oss连接
        OSSClient ossClient = this.getOSSCLient();
        //获取文件的后缀名
        String ext=file.getOriginalFilename();
        ext=ext.substring(ext.lastIndexOf("."));
        String date=sdf.format(new Date());
        //UUid
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        String filename=classify+"/"+date+"/"+uuid+ext;
        String url=null;
        //通过OssClient来获取上传文件后返回的url
        ossClient.putObject(bucketName,filename,new ByteArrayInputStream(file.getBytes()));
        url=suffer_url+filename;
        ossClient.shutdown();
        return url;
    }


}
